/**
 * 
 */
package nc.tb.report;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

import nc.tb.dim.DimMember;
import nc.tb.pub.BusiLevelEntity;

/**
 * @author xuzx
 * 
 */
public class MultiEntityConfig {
	private BusiLevelEntity[] entities = null;
	private boolean isSum = false;
	private boolean isSorted = false;
	private boolean isColLayout = true;
	private HashMap<String, ArrayList<BusiLevelEntity>> hm_level_cache = null;
	private HashMap<String, BusiLevelEntity> hm_pk_cache = null;

	public MultiEntityConfig(BusiLevelEntity[] entities, boolean isSum) {
		super();
		this.entities = entities;
		this.isSum = isSum;
		initCache();
	}

	private void initCache() {
		hm_pk_cache = new HashMap<String, BusiLevelEntity>();
		hm_level_cache = new HashMap<String, ArrayList<BusiLevelEntity>>();
		for(BusiLevelEntity be : entities){
			hm_pk_cache.put(be.getPrimaryKey(), be);
			if(hm_level_cache.get(be.getPk_uplevel()) == null){
				ArrayList<BusiLevelEntity> list = new ArrayList<BusiLevelEntity>();
				list.add(be);
				hm_level_cache.put(be.getPk_uplevel(), list);
			}else{
				hm_level_cache.get(be.getPk_uplevel()).add(be);
			}
		}
		setLevel(null);
	}

	

	private void setLevel(String obj_up) {
		ArrayList<BusiLevelEntity> list = hm_level_cache.get(obj_up);
		if(list == null){
			return;
		}
		for(BusiLevelEntity be : list){
			if(obj_up == null){
				be.setLevel(0);
			}else{
				be.setLevel(hm_pk_cache.get(obj_up).getLevel()+1);
			}
			setLevel(be.getPrimaryKey());
		}
	}

	/**
	 * @return the entities
	 */
	public BusiLevelEntity[] getEntities() {
		if (!isSorted) {
			Arrays.sort(entities, new Comparator<BusiLevelEntity>() {
				public int compare(BusiLevelEntity o1, BusiLevelEntity o2) {
					return o1.getLevel() - o2.getLevel();
				}
			});
		}
		return entities;
	}

	/**
	 * @param entities
	 *            the entities to set
	 */
	public void setEntities(BusiLevelEntity[] entities) {
		this.entities = entities;
	}

	/**
	 * 
	 */
	public MultiEntityConfig() {
	}

	/**
	 * @return the isSum
	 */
	public boolean isSum() {
		return isSum;
	}

	/**
	 * @param isSum
	 *            the isSum to set
	 */
	public void setSum(boolean isSum) {
		this.isSum = isSum;
	}

	public ArrayList<DimMember> getEntityList() {
		ArrayList<DimMember> list = null;
		if (getEntities() != null) {
			list = new ArrayList<DimMember>();
			for (BusiLevelEntity ble : getEntities()) {
				list.add(ble.getEntity());
			}
		}
		return list;
	}

	/**
	 * @return the isColLayout
	 */
	public boolean isColLayout() {
		return isColLayout;
	}

	/**
	 * @param isColLayout
	 *            the isColLayout to set
	 */
	public void setColLayout(boolean isColLayout) {
		this.isColLayout = isColLayout;
	}

}
